﻿using CefSharp;
using CefSharp.WinForms;
using Microsoft.VisualBasic.ApplicationServices;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsLinphoneV.com.amall.common;


namespace VSHT
{
    static class Program
    {
        public static Form1 MainForm;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Process instanceProcess = RunningInstance();
            if (instanceProcess != null)
            {
                HandleRunningInstance(instanceProcess);
            }
            else
            {
                CefSettings settings = new CefSettings();
                // 允许不安全网站访问摄像头
                settings.CefCommandLineArgs.Add("unsafely-treat-insecure-origin-as-secure", Utils.initSystemConfig().default_url);
                settings.CefCommandLineArgs.Add("enable-media-stream", "1");  //开启摄像头

                string cachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MyAppCache");
                settings.CachePath = cachePath;
                Cef.Initialize(settings);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                MainForm = new Form1();
                Application.Run(MainForm);
            }


        }
        private static void HandleRunningInstance(Process instanceProcess)
        {
            ShowWindowAsync(instanceProcess.MainWindowHandle, 1);
            SetForegroundWindow(instanceProcess.MainWindowHandle);
        }

        public static Process RunningInstance()
        {
            Process currentProcess = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);//得到本地计算机所有相同名字的进程
            foreach (Process process in processes)
            {
                //id不相等和文件路径相等的话，那就是同一个软件，返回进程
                if (process.Id != currentProcess.Id)
                {
                    if (process.MainModule.FileName == currentProcess.MainModule.FileName)
                    {
                        return process;
                    }
                }

            }
            return null;
        }
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int Msg);

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
    }
}
